<?php

declare(strict_types=1);

namespace Yansongda\Pay\Plugin\Sbpay;

use Closure;
use Yansongda\Pay\Contract\PluginInterface;
use Yansongda\Pay\Exception\ContainerException;
use Yansongda\Pay\Exception\InvalidConfigException;
use Yansongda\Pay\Exception\ServiceNotFoundException;
use Yansongda\Pay\Logger;
use Yansongda\Pay\Rocket;
//use Yansongda\Pay\Traits\GetSbpayCerts;
use Yansongda\Supports\Str;

use function Yansongda\Pay\get_tenant;
use function Yansongda\Pay\get_sbpay_config;

class PreparePlugin implements PluginInterface
{
//    use GetSbpayCerts;

    /**
     * @throws ContainerException
     * @throws ServiceNotFoundException
     * @throws InvalidConfigException
     */
    public function assembly(Rocket $rocket, Closure $next): Rocket
    {
        Logger::debug('[sbpay][PreparePlugin] 插件开始装载', ['rocket' => $rocket]);

        $rocket->mergePayload($this->getPayload($rocket->getParams()));

        Logger::info('[sbpay][PreparePlugin] 插件装载完毕', ['rocket' => $rocket]);

        return $next($rocket);
    }

    /**
     * @throws ContainerException
     * @throws ServiceNotFoundException
     * @throws InvalidConfigException
     */
    protected function getPayload(array $params): array
    {
        $tenant = get_tenant($params);
        $config = get_sbpay_config($params);

        $init = [
            'pay_method'=>'',
            'merchant_id' => $config['merchant_id'] ?? '',
            'service_id' => $config['service_id'] ?? '',
            'cust_code'=>'',
            'sps_cust_no'=>'',
            'sps_payment_no'=>'',
            'order_id'=>'',
            'item_id'=>'',
            'pay_item_id'=>'',
            'item_name'=>'',
            'tax'=>'',
            'amount'=>'',
            'pay_type'=>'',
            'auto_charge_type'=>'',
            'service_type'=>'',
            'div_settele'=>'',
            'last_charge_month'=>'',
            'camp_type'=>'',
            'tracking_id'=>'',
            'terminal_type'=>'',
            'success_url'=>'',
            'cancel_url'=>'',
            'error_url'=>'',
            'pagecon_url'=>'',
            'free1'=>'',
            'free2'=>'',
            'free3'=>'',
            'free_csv'=>'',

        ];
        
        return array_merge(
            $init,
            array_filter($params, fn ($v, $k) => !Str::startsWith(strval($k), '_'), ARRAY_FILTER_USE_BOTH),
        );
    }
}
